document.addEventListener('DOMContentLoaded', () => {
  const contentContainer = document.querySelector('.funi-content-wrapper');

  if (!contentContainer) {
    console.error('Content container not found');
    return;
  }

  function highlightMenuItem(currentPath) {
    // Remove active class from all menu items
    document.querySelectorAll('.funi-menu-item').forEach(item => {
      item.classList.remove('funi-menu-item-active');
    });

    // Collapse all menu groups initially
    document.querySelectorAll('.funi-menu-group').forEach(group => {
      group.classList.add('collapsed');
      const menuList = group.querySelector('.funi-menu-list');
      if (menuList) {
        menuList.style.height = '0px';
      }
    });

    // Find the active menu item and its parent groups
    const activeLink = document.querySelector(`.funi-menu-link[href="#${currentPath}"]`);
    if (activeLink) {
      const activeItem = activeLink.closest('.funi-menu-item');
      if (activeItem) {
        activeItem.classList.add('funi-menu-item-active');

        // Expand parent menu groups
        let parentGroup = activeItem.closest('.funi-menu-group');
        while (parentGroup) {
          parentGroup.classList.remove('collapsed');
          const menuList = parentGroup.querySelector('.funi-menu-list');
          if (menuList) {
            menuList.style.height = 'auto'; // Allow natural height
          }
          parentGroup = parentGroup.parentElement.closest('.funi-menu-group');
        }
      }
    }
  }

  function loadContent() {
    let fullPath = window.location.hash.substring(1); // Remove '#'
    let pathSegments = fullPath.split('?')[0].split('/'); // Split by '/' and remove query params
    let queryParams = fullPath.split('?')[1] || ''; // Get query params string

    let basePath = '';
    let pageFileName = 'list.html'; // Default page file name

    console.log('loadContent called with fullPath:', fullPath);
    console.log('pathSegments:', pathSegments);

    if (pathSegments.length > 0 && pathSegments[0] === '') {
      // Handle root path, e.g., #/
      pathSegments.shift(); // Remove empty string from split
    }

    if (pathSegments.length === 0) {
      // No hash, load default page
      loadPageContent('pages/default.html');
      highlightMenuItem('');
      return;
    }

    // Determine the base path for the directory and the specific page file
    if (pathSegments.length > 0) {
      const lastSegment = pathSegments[pathSegments.length - 1];
      if (lastSegment === 'add-edit' || lastSegment === 'detail-review') {
        pageFileName = `${lastSegment}.html`;
        basePath = pathSegments.slice(0, -1).join('/'); // Remove the page file name from path segments
      } else {
        basePath = pathSegments.join('/');
        pageFileName = 'list.html'; // Default to list.html for other paths
      }
    }

    const pagePath = `pages/${basePath}/${pageFileName}`;
    console.log('Resolved pagePath:', pagePath);
    loadPageContent(pagePath, queryParams);
    highlightMenuItem(basePath ? `/${basePath}` : ''); // Highlight menu item based on the base path (e.g., /procurement-plan-management)
  }

  function loadPageContent(pagePath, queryParams = '') {
    // Create a hidden iframe to load the content
    const tempIframe = document.createElement('iframe');
    if (!tempIframe) {
      console.error('Failed to create iframe');
      return;
    }

    tempIframe.style.display = 'none';
    tempIframe.style.position = 'absolute';
    tempIframe.style.left = '-9999px';

    if (!document.body) {
      console.error('Document body not available');
      return;
    }

    document.body.appendChild(tempIframe);

    tempIframe.onload = function() {
      try {
        const iframeDoc = tempIframe.contentDocument || tempIframe.contentWindow.document;
        const bodyContent = iframeDoc.body.innerHTML;

        // Load CSS files from the page head
        loadPageCSS(iframeDoc, pagePath);

        // Update the content container
        if (contentContainer) {
          contentContainer.innerHTML = bodyContent;
        } else {
          console.error('Content container not available for update');
          return;
        }

        // Apply current theme to the loaded content
        syncThemeWithContent();

        // Force style recalculation
        setTimeout(() => {
          if (contentContainer) {
            contentContainer.style.display = 'none';
            contentContainer.offsetHeight; // Trigger reflow
            contentContainer.style.display = '';
          }
        }, 50);

        // Set global flag to indicate we're in router mode
        window.FUNI_ROUTER_MODE = true;
        console.log('Set FUNI_ROUTER_MODE to true');

        // Execute any scripts in the loaded content
        executeScripts(contentContainer);

        // Call page initialization function if available
        setTimeout(() => {
          if (window.initializePage && typeof window.initializePage === 'function') {
            window.initializePage();
          }
        }, 100);

        // Pass query parameters to the loaded page if needed
        if (queryParams && window.loadedPageInit) {
          const params = new URLSearchParams(queryParams);
          window.loadedPageInit(params);
        }

        // Remove the temporary iframe
        document.body.removeChild(tempIframe);

      } catch (error) {
        console.error('Error loading page:', error);
        if (contentContainer) {
          contentContainer.innerHTML = `
            <div style="padding: 20px; text-align: center; color: var(--funi-danger-color);">
              <h3>页面加载失败</h3>
              <p>无法加载页面: ${pagePath}</p>
              <p>错误信息: ${error.message}</p>
              <p>请确保页面文件存在且路径正确</p>
            </div>
          `;
        }
        // Remove the temporary iframe even on error
        if (tempIframe.parentNode) {
          document.body.removeChild(tempIframe);
        }
      }
    };

    tempIframe.onerror = function() {
      console.error('Failed to load page:', pagePath);
      if (contentContainer) {
        contentContainer.innerHTML = `
          <div style="padding: 20px; text-align: center; color: var(--funi-danger-color);">
            <h3>页面加载失败</h3>
            <p>无法加载页面: ${pagePath}</p>
            <p>请检查文件是否存在</p>
          </div>
        `;
      }
      // Remove the temporary iframe
      if (tempIframe.parentNode) {
        document.body.removeChild(tempIframe);
      }
    };

    // Load the page
    if (tempIframe && pagePath) {
      tempIframe.src = pagePath;
    } else {
      console.error('Cannot load page: iframe or pagePath is null', { tempIframe, pagePath });
    }
  }

  // Function to load CSS files from page
  function loadPageCSS(iframeDoc, pagePath) {
    // Get all link elements from the page
    const linkElements = iframeDoc.querySelectorAll('link[rel="stylesheet"]');
    const pageDir = pagePath.substring(0, pagePath.lastIndexOf('/') + 1);
    
    console.log('Loading CSS for page:', pagePath);
    console.log('Found CSS links:', linkElements.length);

    linkElements.forEach(link => {
      const href = link.getAttribute('href');
      if (href && !isAbsoluteURL(href)) {
        // Convert relative path to absolute path
        const absoluteHref = resolveRelativePath(pageDir, href);
        console.log('Resolved CSS path:', href, '->', absoluteHref);

        // Check if this CSS is already loaded
        const existingLink = document.querySelector(`link[href="${absoluteHref}"]`);
        if (!existingLink) {
          // Create and append new link element
          const newLink = document.createElement('link');
          newLink.rel = 'stylesheet';
          newLink.href = absoluteHref;
          newLink.setAttribute('data-page-css', 'true');
          document.head.appendChild(newLink);
          console.log('Added CSS link:', absoluteHref);
        } else {
          console.log('CSS already loaded:', absoluteHref);
        }
      }
    });
  }

  function isAbsoluteURL(url) {
    return /^https?:\/\//.test(url) || url.startsWith('/');
  }

  function resolveRelativePath(basePath, relativePath) {
    // Handle relative paths like ../../assets/css/file.css
    // basePath is like "pages/procurement-plan-management/"
    // relativePath is like "../../assets/css/funi-list.css"

    // Remove the filename from basePath if it exists
    let baseDir = basePath;
    if (!baseDir.endsWith('/')) {
      baseDir = baseDir.substring(0, baseDir.lastIndexOf('/') + 1);
    }

    // Split paths and filter out empty segments
    const baseSegments = baseDir.split('/').filter(segment => segment);
    const relativeSegments = relativePath.split('/').filter(segment => segment);

    let resultSegments = [...baseSegments];

    for (const segment of relativeSegments) {
      if (segment === '..') {
        resultSegments.pop();
      } else if (segment !== '.') {
        resultSegments.push(segment);
      }
    }

    return resultSegments.join('/');
  }

  // Function to synchronize theme with loaded content
  function syncThemeWithContent() {
    const isDarkTheme = document.body.classList.contains('dark-theme');
    const contentBody = contentContainer.querySelector('#app') || contentContainer;
    if (contentBody) {
      if (isDarkTheme) {
        contentBody.classList.add('dark-theme');
      } else {
        contentBody.classList.remove('dark-theme');
      }
    }
  }

  // Function to execute scripts in loaded content
  function executeScripts(container) {
    const scripts = container.querySelectorAll('script');
    scripts.forEach(script => {
      const newScript = document.createElement('script');
      if (script.src) {
        newScript.src = script.src;
      } else {
        newScript.textContent = script.textContent;
      }
      // Copy attributes
      Array.from(script.attributes).forEach(attr => {
        newScript.setAttribute(attr.name, attr.value);
      });
      script.parentNode.replaceChild(newScript, script);
    });
  }

  // Load content on initial page load
  loadContent();

  // Listen for hash changes
  window.addEventListener('hashchange', loadContent);

  // Observe changes to the body's classList to sync theme dynamically
  const observer = new MutationObserver(mutations => {
    mutations.forEach(mutation => {
      if (mutation.type === 'attributes' && mutation.attributeName === 'class') {
        syncThemeWithContent();
      }
    });
  });

  observer.observe(document.body, { attributes: true });

  // Handle menu clicks to update hash
  document.querySelectorAll('.funi-menu-link').forEach(link => {
    link.addEventListener('click', event => {
      event.preventDefault();
      const href = link.getAttribute('href');
      if (href && href.startsWith('#')) {
        window.location.hash = href.substring(1);
      }
    });
  });
});
